<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Model\Orders;
use App\Http\Model\OrdersInfo;
use Config;

class OrdersController extends Controller{
	public function orders(){
		$orders = new Orders;
		$ordersInfo = $orders->where('user_id',session('uid'))->get();
		foreach ($ordersInfo as $k => $v) {
			$ordersInfo[$k]["sum_num"] = 0;
			$ordersInfo[$k]["sum_price"] = 0;
			$ordersInfo[$k]["sum_express"] = 0;
			foreach ($v->ordersInfo as $kk => $vv) {
				$ordersInfo[$k]["sum_num"] += $vv->num;
				$ordersInfo[$k]["sum_price"] += $vv->num * $vv->price;
				$ordersInfo[$k]["sum_express"] += $vv->express;
			}

		}
		return view("home.orders.orders", ["ordersInfo"=>$ordersInfo]);
	}
	public function goodsReceipt(Request $request){
		$id = $request->input("id");
		$orders = new Orders;
		$ordersInfo = $orders->find($id);
		$ordersInfo->status = 4;
		$ordersInfo->save();
		$nowTime = date("Y-m-d H:i:s");
		$ordersData = new OrdersInfo;
		$ordersData->where("orders_id", $id)->update(["refund_status"=>0, "receipt_at"=>$nowTime]);
		echo 1;die;
	}
	// 快递查询
    public function logistic($id){
        $orders = new Orders;
        $ordersInfo = $orders->find($id);
        $num = $ordersInfo->num;
        // $num = '51010904478878935';
        $logistic_code = $ordersInfo->logistic_code;
        // $logistic_code = '3976331681071';
        $logistic_company = Config::get('app.kdn_company_name');
        // $logistic_company = "YD";
        $logisticResult = json_decode($this->getOrderTracesByJson($num, $logistic_code, $logistic_company));
		// $logisticResult = 1;
        // dd($logisticResult);
        return view("home.orders.logistic", ["logistic"=>$logisticResult, "ordersInfo"=>$ordersInfo]);
    }

    /**
     * Json方式 查询订单物流轨迹
     */
    public function getOrderTracesByJson($num, $logistic_code, $logistic_company){
        $requestData = "{'OrderCode':'$num','ShipperCode':'$logistic_company','LogisticCode':'$logistic_code'}";

        $datas = array(
            'EBusinessID' => Config::get('app.kdn_user_id'),
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, Config::get('app.kdn_api_key'));
        $result = $this->sendPost('http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx', $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
    //删除订单
    public function deleteOrders(Request $request){
        $order = new Orders;
        $ordersInfo = new OrdersInfo;
        $id = $request->input('id');
        $res = $order->where('id',$id)->delete();
        $res1 = $ordersInfo->where('orders_id',$id)->delete();
        if($res && $res1){
            echo 1;
        }else{
            echo 0;
        }
    }
}
